// 蓝牙搜寻
import $store from '@/store/index'
import storage from '@/static/js/storage'
import deviceData from '@/utils/ble-handler/getBleData.js'

// 初始化蓝牙适配器
function openBluetoothAdapter() {
    return new Promise((resolve, reject) => {
        if (!uni.openBluetoothAdapter()) {
            reject('未知错误!')
        } else {
            uni.openBluetoothAdapter({
                success: (res) => {
                    resolve(res)
                },
                fail: (err) => {
                    reject(err)
                }
            })
        }
    })
}

const store = {
    state: {
        loading: false,
        tips: '搜寻中',
        searchType: 'get', // 搜寻类型（get:查询, set:配置 ）
        bleState: false, // 蓝牙状态
        interval: null // 定时器
    },
    mutations: {
        // 设置蓝牙开关状态
        SET_BLE_STATE(state, boolean) {
            state.bleState = boolean
        },
        // 设置loading
        SET_LOADING(state, boolean) {
            state.loading = boolean
        },
        // 设置提示文字
        SET_TIPS(state, value) {
            state.tips = value
        },
        // 设置定时
        SET_TIMER(state, value) {
            state.timer = value
        },
        // 设置查询类型
        SET_SEARCH_TYPE(state, value) {
            state.searchType = value
        },
        // 清除定时器
        CLEAR_INTERVAL(state) {
            if (!state.interval) {
                return false
            }
            clearInterval(state.interval)
            state.interval = null
        }
    },
    actions: {
        // 搜寻设备
        search_devices({ commit, state }) {
            commit('SET_TIPS', '搜寻中')
            uni.onBluetoothDeviceFound(devices => {
                let data = devices.devices[0] || null
                // 排除非本系统设备
                if (!data.name.includes('BLEPDF')) return
                const resData = deviceData(data, type)
                const type = state.searchType
                if (type == 'get') {
                    if (data.state != 'setout') {
                        $store.dispatch('read-tag/read_searchRes', resData)
                    }
                } else {
                    $store.dispatch('set-tag/set_searchRes', resData)
                }
            })
        },
        // 停止搜寻
        stop_bleSearch({ commit }) {
            commit('CLEAR_INTERVAL')
            commit('SET_LOADING', false)
            commit('SET_TIPS', '搜寻中')
            uni.stopBluetoothDevicesDiscovery({
                success: res => {
                    commit('SET_BLE_STATE', false)
                }
            })
        },
        // 错误提示并延迟1.5秒关闭loading
        err_message({ commit }, err) {
            $store.commit('ble-info/BLE_ERR_TOAST', err.errCode || err)
            commit('SET_TIPS', '搜寻中')
            setTimeout(() => {
                commit('SET_LOADING', false)

            }, 1500)
        },
        // 定时搜寻
        search_timed({ dispatch, state }) {
            let timer = 0
            // 搜寻设备
            dispatch('search_devices')
            // 设置定时器
            state.interval = setInterval(() => {
                timer++
                if (timer >= 6) {
                    dispatch('stop_bleSearch') // 时间到停止搜寻
                }
            }, 1000)
        },
        // 搜寻设置
        // 判断是否有查询码，如果有查询码先设置查询码数据体
        search_config({ dispatch, commit }, type) {
            // 配置放行
            if (type == 'set') {
                dispatch('search_timed')
                return false
            }
            // 非查询码放行
            const pageType = $store.state['read-tag'].pageType
            console.log('pageType', pageType)
            if (pageType == 'default') {
                dispatch('search_timed')
                return false
            }
            // 查询码页面先设置查询码数据体
            storage('get', 'checkCode').then(res => {
                let codeList = []
                try {
                    codeList = JSON.parse(res)
                } catch (e) { }
                let arr = []
                codeList.forEach(item => {
                    if (item) {
                        arr.push({
                            code: item,
                            data: []
                        })
                    }
                })
                $store.commit('read-tag/SET_CODE_DATA', arr)
                dispatch('search_timed')
            })
        },
        /**
         * 开始搜寻蓝牙设备
         * @param {*} type 类型（set: 配置, get: 查询）
         */
        start_bleSearch({ dispatch, commit }, type) {
            commit('SET_SEARCH_TYPE', type) // 设置类型
            commit('SET_LOADING', true)
            commit('SET_TIPS', '初始化蓝牙')
            openBluetoothAdapter().then(res => {
                uni.startBluetoothDevicesDiscovery({
                    success: res => {
                        commit('SET_BLE_STATE', true)
                        dispatch('search_config', type)
                    },
                    fail: err => {
                        dispatch('err_message', err)
                    }
                })
            }).catch(err => {
                dispatch('err_message', err)
            })
        }
    }
}

export default store